<?php
/*
Plugin Name: 腾讯云CDN
Plugin URI: https://www.beizigen.com/3653.html
Description: 腾讯云CDN缓存自动刷新。
Version: 1.0.2
Author: 背字根
Author URI: https://www.beizigen.com/
Text Domain: tencent-cdn
License: GPL v3 or later
License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/

require_once('includes/class-cdn.php');
require_once('includes/functions.php');

function cdn_control() {
	$defaults = array(
		'secret_id' => '',
		'secret_key' => '',
        'flush_cache' => '',
	);
    
	$options = get_option('tencent_cdn');
	$options = unserialize($options);
	$options = wp_parse_args($options, $defaults);

	$error = new WP_Error;

	if(isset($_POST['action'])) {
		//插件设置
		if('setting' == $_POST['action']) {
			foreach($options as $key=>$val) {
				if(isset($_POST[$key])) {
                    if(is_array($_POST[$key])) {
                        $val = join(',', $_POST[$key]);
                        $val = sanitize_text_field($val);
                    } else {
                        $val = sanitize_text_field($_POST[$key]);
                    }
					$options[$key] = $val;
				}
			}

			update_option('tencent_cdn', serialize($options));
			$error->add('info', '设置保存成功！');
		}
	}
	
    $options['flush_cache'] = explode(',', $options['flush_cache']);
	$tab = isset($_GET['tab']) ? $_GET['tab'] : 'tools';
	$page = admin_url('options-general.php?page=tencent-cdn');

?>
<link rel="stylesheet" href="<?php echo plugin_dir_url(__FILE__ ); ?>css/tencent-cdn.css">
<div class="mywrap wp-clearfix">
	<nav id="tabs">
		<ul>
			<li<?php echo 'tools' == $tab ? ' class="active"' : ''; ?>><a href="<?php echo $page; ?>&amp;tab=tools">缓存刷新</a></li>
			<li<?php echo 'setting' == $tab ? ' class="active"' : ''; ?>><a href="<?php echo $page; ?>&amp;tab=setting">插件设置</a></li>
		</ul>
	</nav>

	<div id="content-box">
		<?php
			if($error->has_errors()) {
				if($error->get_error_message('error')) {
					echo '<div class="notice is-dismissible error">' . $error->get_error_message('error') . '</div>';
				} else {
					echo '<div class="notice is-dismissible success">' . $error->get_error_message('info') . '</div>';
				}
			}
		?>
		<?php if('tools' == $tab) : 
            $tencentCDN = new tencentCDN;
            $quota = $tencentCDN->quota();
            $flush_type = 'UrlPurge';
            if($quota) {
                if(isset($_POST['action']) && 'flush' == $_POST['action'] && !empty($_POST['urls'])) {
                    $urls = sanitize_textarea_field($_POST['urls']);
                    $urls = explode("\n", $urls);
                    $flush_type = $_POST['flush_type'];
                    $urls = array_slice($urls, 0, $quota[$flush_type][0]['Batch']);
                    $flush = $tencentCDN->flush($urls, $flush_type);
                    if($flush === true) {
                        $quota = $tencentCDN->quota();
                        echo '<div class="notice is-dismissible success">刷新缓存成功！</div>';
                    } else {
                        echo '<div class="notice is-dismissible error">' . $flush . '</div>';
                    }
                }

                $current_quota = $quota[$flush_type];
        ?>
			<form method="post" action="<?php echo $page; ?>&amp;tab=tools">
                <p>
                    <select id="flush-type" name="flush_type">
                        <option value="UrlPurge"<?php echo 'UrlPurge' == $flush_type ? ' selected' : ''; ?>>URL刷新</option>
                        <option value="PathPurge"<?php echo 'PathPurge' == $flush_type ? ' selected' : ''; ?>>目录刷新</option>
                    </select>
                </p>
                <p style="margin-bottom: 0;">
                    <textarea id="urls" name="urls" rows="5" cols="50" class="large-text code"></textarea>
                </p>
                <p id="remind" class="description">URL 必须包含 http:// 或 https://，一行一个。</p>
                <p class="description">中国境内 - 今日剩余个数：
                    <span id="mainland" class="txt-impt"><?php echo $current_quota[0]['Available']; ?></span>
                    &nbsp;&nbsp;单次可提交：<span id="mainland-max"><?php echo $current_quota[0]['Available'] - $current_quota[0]['Batch'] > 0 ? $current_quota[0]['Batch'] : $current_quota[0]['Available']; ?></span>
                </p>
                <p class="description">中国境外 - 今日剩余个数：
                    <span id="overseas" class="txt-impt"><?php echo $current_quota[1]['Available']; ?></span>
                    &nbsp;&nbsp;单次可提交：<span id="overseas-max"><?php echo $current_quota[1]['Available'] - $current_quota[1]['Batch'] > 0 ? $current_quota[1]['Batch'] : $current_quota[1]['Available']; ?></span>
                </p>
                <p>
					<input class="button button-primary" type="submit" value="刷新缓存" onclick="disabled=true; submit();">
					<input type="hidden" name="action" value="flush">
				</p>
			</form>
            <script type="text/javascript">
                jQuery(document).ready(function() {
                    var quota = '<?php echo json_encode($quota); ?>';
                    quota = JSON.parse(quota);
                    jQuery("#flush-type").change(function() {
                        var flush_type = jQuery(this).find("option:selected").val();
                        var current_quota = quota[flush_type];
                        var mainland_max = current_quota[0]["Available"] - current_quota[0]["Batch"] > 0 ? current_quota[0]["Batch"] : current_quota[0]["Available"];
                        var overseas_max = current_quota[1]["Available"] - current_quota[1]["Batch"] > 0 ? current_quota[1]["Batch"] : current_quota[1]["Available"];
                        jQuery("#mainland").text(current_quota[0]["Available"]);
                        jQuery("#overseas").text(current_quota[1]["Available"]);
                        jQuery("#mainland-max").text(mainland_max);
                        jQuery("#overseas-max").text(overseas_max);
                    });
                    
                    jQuery("#urls").bind("input propertychange", function() {
                        var urls = jQuery(this).val();
                        urls = urls.split("\n");
                        var urlcount = urls.length;
                        var flush_type = jQuery("#flush-type").find("option:selected").val();
                        var current_quota = quota[flush_type];
                        var free = current_quota[0]["Batch"]-urlcount;
                        if(free > 0) {
                            free = '还可以输入<span class="txt-impt">' + free + '</span>个';
                        } else {
                            free = '已超出<span class="txt-impt">' + Math.abs(free) + '</span>个';
                        }
                        jQuery("#remind").html('已输入<span class="txt-impt">' + urlcount + '</span>个，' + free);
                    });
                });
            </script>
		<?php
            } else {
                echo '<p>请先设置API信息。</p>';
            }

            endif;
        ?>

		<?php if('setting' == $tab) : ?>
			<form method="post" action="<?php echo $page; ?>&amp;tab=setting">
				<table class="form-table">
					<tbody>
						<tr>
							<th scope="row">
								<label for="secret-id">Secret ID</label>
							</th>
							<td>
								<input id="secret-id" name="secret_id" class="regular-text code" type="text" value="<?php echo $options['secret_id']; ?>" required>
								<p class="description">登录<a href="https://console.cloud.tencent.com/cam/capi" target="_blank" rel="nofollow">API 密钥管理 </a>创建。</p>
							</td>
						</tr>
						<tr>
							<th scope="row">
								<label for="secret-key">Secret Key</label>
							</th>
							<td>
								<input id="secret-key" name="secret_key" class="regular-text code" type="text" value="<?php echo $options['secret_key']; ?>" required>
								<p class="description">登录<a href="https://console.cloud.tencent.com/cam/capi" target="_blank" rel="nofollow">API 密钥管理</a>创建。</p>
							</td>
						</tr>
                        <tr>
							<th scope="row">
								<label for="flush-cache">缓存刷新</label>
							</th>
							<td>
                                <p><label><input type="checkbox" name="flush_cache[]" value="addpost"<?php echo $options['flush_cache'] && in_array('addpost', $options['flush_cache']) ? ' checked' : ''; ?>> 发表文章刷新首页、分类页、标签页缓存</label></p>
                                <p><label><input type="checkbox" name="flush_cache[]" value="uppost"<?php echo $options['flush_cache'] && in_array('uppost', $options['flush_cache']) ? ' checked' : ''; ?>> 更新文章刷新文章页缓存</label></p>
                                <p><label><input type="checkbox" name="flush_cache[]" value="changepost"<?php echo $options['flush_cache'] && in_array('changepost', $options['flush_cache']) ? ' checked' : ''; ?>> 文章状态变更刷新文章页、首页、分类页、标签页缓存</label></p>
                                <p><label><input type="checkbox" name="flush_cache[]" value="term"<?php echo $options['flush_cache'] && in_array('term', $options['flush_cache']) ? ' checked' : ''; ?>> 删除分类/标签刷新缓存</label></p>
                                <p><label><input type="checkbox" name="flush_cache[]" value="newcomment"<?php echo $options['flush_cache'] && in_array('newcomment', $options['flush_cache']) ? ' checked' : ''; ?>> 发表评论刷新页面缓存</label></p>
                                <p><label><input type="checkbox" name="flush_cache[]" value="editcomment"<?php echo $options['flush_cache'] && in_array('editcomment', $options['flush_cache']) ? ' checked' : ''; ?>> 变更评论刷新页面缓存</label></p>
                            </td>
                        </tr>
					</tbody>
				</table>
				<p>
					<input class="button-primary" type="submit" value="保存设置">
					<input type="hidden" name="action" value="setting">
				</p>
			</form>
		<?php endif; ?>
	</div>
</div>

<?php
}

//添加菜单
function cdn_menu() {
    add_options_page('腾讯云CDN', '腾讯云CDN', 'administrator', 'tencent-cdn', 'cdn_control');
	//add_menu_page('腾讯云CDN', '腾讯云CDN', 'administrator', 'tencent-cdn', 'cdn_control', 'dashicons-cloud', 998);
}
add_action('admin_menu', 'cdn_menu');

//插件页面设置链接
add_filter('plugin_action_links', function($links, $file) {
	if($file == plugin_basename(__FILE__)) {
		array_unshift($links, '<a href="options-general.php?page=tencent-cdn">设置</a>');
	}
	return $links;
}, 10, 2);
?>